import React, { Component } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  TreeSelect,
  message,
  Spin,
  Modal,
  Tag
} from "antd";
import { connect } from "dva";
import dataInfo from "./data";
// import TopInfo from "./components/TopInfo";
import SelectModal from "../../recommendCenter/add/components/SelectModal";
import BottomInfo from "./components/BottomInfo";
import styles from "./SupervisoryAdd.less";
import FixedBottomWrapper from "../../../components/FixedBottomWrapper";

const { TextArea } = Input;
const monitorTypeText = ["", "消息源", "渠道名称", "渠道类型", "计划名称"];
@connect(stores => ({
  dsDetail: stores.adddataSource,
  messageSave: stores.saveMessage,
  EditplanData: stores.addPlan,
  supervisoryModelData: stores.supervisoryModel,
  channelDictionaryModel: stores.channelDictionaryModel
}))
@Form.create()
class SupervisoryAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      workDisable: true,
      ruleType: "",
      ruleDisable: true,
      ruleChannel: "",
      ownerDeptName: "",
      manager: [],
      alarmTarget: [], // new 告警目标
      alarmTargetId: [], // new 告警目标的id
      borderVisible: false,
      owner: [], // 管理员
      selectVisible: false,
      timeVisible: false,
      radioVisible: false,
      monitorId: "",
      loadingEdit: false,
      ownerDept: "",
      resendmonitorType: "",
      // xxxxx
      monitorName: "",
      monitorType: null, // 监控类型
      msgSourceList: [], // 消息源列表
      chooseOwner: true, // 判断是否进行的是管理员的选择而不是告警目标的选择
      reporter: [], // 告警目标
      reporterId: "", // 告警目标的id
      limitUnit: 3, // 告警配置限制时间单位
      restrainUnit: 1, // 告警配置抑制时间单位
      monitorTypeText: "", // 监控类型的第二个选项
      restrainValue: "", // 告警抑制次数
      limitValue: "", // 限制次数
      getPlanList: [] // 智能推送计划列表
    };
    this.key = {};
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {}
    });
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });

    this.msgSourceList();
    const { location } = this.props;
    const search = decodeURI(location.search);

    const key = JSON.parse(search.split("=")[1]);
    this.key = key;
    if (key.operate === "mod") {
      this.setState({ loadingEdit: false });
      this.getDetail(key.monitorId);
    } else {
      this.setState({ loadingEdit: true });
    }
    this.getPlanList();
  }

  // 获取消息源列表
  msgSourceList = () => {
    const { dispatch } = this.props;
    dispatch({ type: "supervisoryModel/msgSourceList", payload: {} }).then(
      res => {
        this.setState({
          msgSourceList: res.datas
        });
      }
    );
  };

  // 获取智能推送列表
  getPlanList = () => {
    const { dispatch } = this.props;
    dispatch({ type: "supervisoryModel/getPlanList", payload: {} }).then(
      res => {
        this.setState({
          getPlanList: res.datas
        });
      }
    );
  };

  confirm = (e, desc) => {
    const { chooseOwner } = this.state;
    if (chooseOwner) {
      this.setState({ owner: desc, manager: e, selectVisible: false });
      this.props.form.setFieldsValue({ owner: desc });
    } else {
      this.setState(
        {
          reporter: desc,
          reporterId: e,
          alarmTargetId: e,
          alarmTarget: desc,
          borderVisible: false,
          selectVisible: false
        },
        () => {
          this.props.form.setFieldsValue({ alarmTargetTip: Math.random() });
        }
      );
      // this.props.form.setFieldsValue({ reporter: desc });
    }

    // this.props.form.setFieldsValue({ owner: 1 });
  };

  getDetail = id => {
    const { dispatch } = this.props;
    dispatch({
      type: "supervisoryModel/queryServisory",
      payload: { monitorId: id }
    }).then((res = {}) => {
      if (res.success) {
        const {
          monitorId = "",
          monitorName = "",
          monitorType = "",
          monitorMsgSourceId = null,
          monitorChannelId = null,
          monitorChannelType = "",
          reportChannelId = "",
          reportChannelName = "",
          reporter = [],
          owner = [],
          ownerDept = "",
          ownerDeptName = "",
          monitorDescription = "",
          limitUnit = 2,
          limitValue = "",
          restrainValue = "",
          restrainUnit = 1,
          monitorPlanId = ""
        } = res.datas;
        this.setState({
          monitorId,
          monitorName,
          monitorType, // 监控类型
          reportChannelName,
          // reporter: this.handleReporter(reporter), // 告警目标
          // reporter: reporter[0].name, // 告警目标
          alarmTarget: this.handleAlarmTarget(reporter, true),
          alarmTargetId: this.handleAlarmTarget(reporter, false),
          reporterId: reportChannelId, // 告警目标的id
          // monitorTypeText: "", // 监控类型的第二个选项
          owner: owner[0].name,
          ownerDept,
          ownerDeptName,
          monitorDescription,
          limitUnit,
          limitValue,
          restrainValue,
          restrainUnit,
          monitorPlanId
        });
        let monitorTypeTextRes = "";
        if (monitorType === 1) {
          monitorTypeTextRes = monitorMsgSourceId;
        }
        if (monitorType === 2) {
          monitorTypeTextRes = monitorChannelId;
        }
        if (monitorType === 3) {
          monitorTypeTextRes = monitorChannelType;
        }
        if (monitorType === 4) {
          monitorTypeTextRes = monitorPlanId;
        }
        this.setState({
          monitorTypeText
        });
        const { form } = this.props;
        form.setFieldsValue({
          monitorName,
          monitorType,
          monitorTypeText: monitorTypeTextRes,
          ownerDept,
          reportChannel: reportChannelId,
          ownerDeptName,
          monitorDescription,
          owner: [owner[0].name],
          reporter: [reporter[0].name],
          alarmTargetTip: Math.random()
        });
        this.setState({ loadingEdit: true });
      }
    });
  };

  handleReporter = () => {
    const reporter = [];
    this.state.alarmTargetId.forEach((item, index) => {
      reporter.push({
        key: item,
        name: this.state.alarmTarget[index]
      });
    });
    return reporter;
  };

  handleAlarmTarget = (reporter = [], isAlarmTarget = true) => {
    const strArr = [];
    if (reporter.length) {
      reporter.forEach(item => {
        const val = isAlarmTarget ? item.name : item.key;
        strArr.push(val);
        return null;
      });
    }
    return strArr;
  };

  closeModal = () => {
    this.setState({
      selectVisible: false
    });
  };

  departGet = (e, departmentName) => {
    this.setState({
      ownerDeptName: departmentName[0]
    });
  };

  handleSubmit = (e, type) => {
    const {
      ownerDeptName,
      manager,
      // xxxx
      monitorType,
      // reporterId,
      limitUnit,
      limitValue,
      restrainValue,
      restrainUnit
    } = this.state;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (this.state.alarmTargetId.length <= 0) {
        this.setState({
          borderVisible: true
        });
      }
      if (!err) {
        const { dispatch, EditplanData } = this.props;
        const { channelList = [] } = EditplanData;

        const payload = {
          monitorName: values.monitorName,
          reportChannelId: values.reportChannel,
          monitorType: values.monitorType,
          owner: [{ name: values.owner[0], key: manager[0] }],
          reporter: this.handleReporter(),
          // reporter: [{ name: values.reporter[0], key: reporterId[0] }],
          monitorDescription: values.monitorDescription,
          ownerDept: values.ownerDept,
          ownerDeptName,
          reportChannelName: channelList.filter(
            item => item.pushChannelId === values.reportChannel
          )[0].description,
          limitUnit,
          limitValue,
          restrainValue,
          restrainUnit
        };

        if (monitorType === 1) {
          payload.monitorMsgSourceId = values.monitorTypeText;
        }
        if (monitorType === 2) {
          payload.monitorChannelId = values.monitorTypeText;
        }
        if (monitorType === 3) {
          payload.monitorChannelType = values.monitorTypeText;
        }
        if (monitorType === 4) {
          payload.monitorPlanId = values.monitorTypeText;
        }
        const { monitorId } = this.state;
        if (monitorId) {
          payload.monitorId = monitorId;
        }
        dispatch({
          type:
            type === "save"
              ? "supervisoryModel/savesServisory"
              : "supervisoryModel/commitServisory",
          payload
        }).then((res = {}) => {
          if (res.success) {
            const { history } = this.props;
            message.success(type === "save" ? "保存成功" : "发布成功");
            history.push("/messageCenter/supervisoryManager");
          } else {
            message.error(`${res.errMsg}`);
          }
        });
      }
    });
  };

  getChannel = e => {
    const { EditplanData } = this.props;
    const { channelList = [] } = EditplanData;
    let monitorType = "";
    channelList.forEach(item => {
      if (String(item.pushChannelId) === String(e)) {
        monitorType = item.description;
      }
    });
    this.setState({
      ruleChannel: e,
      resendmonitorType: monitorType
    });
  };

  getRule = e => {
    this.setState({
      ruleType: e.target.value,
      ruleDisable: e.target.value !== 2
    });
  };

  getLimitUnit = e => {
    this.setState({
      limitUnit: e
    });
  };

  getRestrainUnit = e => {
    this.setState({
      restrainUnit: e
    });
  };

  getLimitValue = e => {
    this.setState({
      limitValue: e || e === 0 ? e : ""
    });
  };

  getRestrainValue = e => {
    this.setState({
      restrainValue: e || e === 0 ? e : ""
    });
  };

  onBack = () => {
    const { history } = this.props;
    Modal.confirm({
      title: "是否直接关闭此监控管理？",
      onOk() {
        history.push("/messageCenter/supervisoryManager");
      },
      onCancel() {}
    });
  };

  getWorkTimeType = e => {
    this.setState({
      workTime: e.target.value,
      workDisable: e.target.value !== 6,
      radioVisible: false,
      timeVisible: false
    });
  };

  channelSet = e => {
    const {
      form: { resetFields }
    } = this.props;
    resetFields(["monitorTypeText"]);
    this.setState({
      monitorType: e
    });
  };

  chooseMonitorTypeText = e => {
    this.setState({
      monitorTypeText: e
    });
  };

  onCloseTag = (e, indexs) => {
    e.stopPropagation();
    const { alarmTargetId, alarmTarget } = this.state;
    const id = alarmTargetId.filter((item, index) => index !== indexs);
    const desc = alarmTarget.filter((item, index) => index !== indexs);
    this.setState(
      {
        alarmTargetId: id,
        alarmTarget: desc
      },
      () => {
        const flag = this.state.alarmTarget.length;
        this.props.form.setFieldsValue({
          alarmTargetTip: flag ? Math.random() : ""
        });
      }
    );
  };

  render() {
    const { dsDetail, EditplanData, channelDictionaryModel = {} } = this.props;
    const { channelList = [] } = EditplanData;
    const { getFieldDecorator } = this.props.form;
    const { orgTree = [] } = dsDetail;
    const {
      manager,
      owner,
      alarmTarget,
      alarmTargetId,
      selectVisible,
      loadingEdit,
      monitorType,
      msgSourceList = [],
      chooseOwner,
      restrainUnit,
      limitUnit,
      restrainValue,
      limitValue,
      getPlanList
    } = this.state;

    const { formItemLayout } = dataInfo;
    const { channelsTypesData = [] } = channelDictionaryModel;
    const monitorTypeSelect = [
      [],
      msgSourceList,
      channelList,
      // 在监控注册和监控编辑，暂时只保留监控类型-短信
      channelsTypesData.filter(elem => elem.des === "短信渠道"),
      getPlanList
    ];
    return (
      <FixedBottomWrapper
        className={styles.root}
        footer={
          <React.Fragment>
            <Button
              type="primary"
              style={{ marginLeft: 20 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e, "submit")}
            >
              提交
            </Button>
            <Button
              style={{ marginLeft: 8, marginRight: 8 }}
              // htmlType="submit"
              onClick={e => this.handleSubmit(e, "save")}
            >
              保存
            </Button>
            <Button onClick={this.onBack}>取消</Button>
          </React.Fragment>
        }
      >
        <Spin spinning={!loadingEdit}>
          <div className={styles.topInfo}>
            <span className={styles.basic}>
              {this.key.operate === "mod" ? "监控编辑" : "监控新增"}
            </span>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item {...formItemLayout} label="监控名称">
                {getFieldDecorator("monitorName", {
                  rules: [
                    {
                      required: true,
                      message: "监控名称不能为空"
                    },
                    {
                      max: 20,
                      message: "监控名称少于20个字"
                    }
                  ]
                })(
                  <Input
                    style={{ width: 466 }}
                    placeholder="请输入监控名称名称"
                  />
                )}
              </Form.Item>
              <Form.Item
                required
                {...formItemLayout}
                label="监控类型"
                style={{ marginBottom: 0 }}
              >
                <Form.Item style={{ display: "inline-block", width: 200 }}>
                  {getFieldDecorator("monitorType", {
                    rules: [
                      {
                        required: true,
                        message: "请选择监控类型"
                      }
                    ]
                  })(
                    <Select
                      placeholder="请选择监控类型"
                      style={{ width: 180, marginRight: 20 }}
                      onChange={this.channelSet}
                    >
                      <Select.Option value={1}>消息源</Select.Option>
                      <Select.Option value={2}>渠道名称</Select.Option>
                      <Select.Option value={3}>渠道类型</Select.Option>
                      {/* <Select.Option value={4}>智能推送</Select.Option> */}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  style={{
                    display: "inline-block"
                  }}
                >
                  {getFieldDecorator("monitorTypeText", {
                    rules: [
                      {
                        required: true,
                        message: `请选择${
                          monitorType ? monitorTypeText[monitorType] : ""
                        }`
                      }
                    ]
                  })(
                    <Select
                      placeholder={`请选择${
                        monitorType ? monitorTypeText[monitorType] : ""
                      }`}
                      style={{ width: 265 }}
                      onChange={this.chooseMonitorTypeText}
                      disabled={monitorType === null}
                    >
                      {monitorType &&
                        monitorTypeSelect[monitorType].length &&
                        monitorTypeSelect[monitorType].map((item, index) => {
                          if (monitorType === 1) {
                            return (
                              <Select.Option key={index} value={item.sourceId}>
                                {item.sourceName}
                              </Select.Option>
                            );
                          }
                          if (monitorType === 2) {
                            return (
                              <Select.Option
                                key={item.pushChannelId}
                                value={item.pushChannelId}
                              >
                                {item.description}
                              </Select.Option>
                            );
                          }
                          if (monitorType === 3) {
                            return (
                              <Select.Option
                                key={item.value}
                                value={item.value}
                              >
                                {item.des}
                              </Select.Option>
                            );
                          }
                          if (monitorType === 4) {
                            return (
                              <Select.Option
                                key={item.planId}
                                value={item.planId}
                              >
                                {item.planName}
                              </Select.Option>
                            );
                          }
                          return (
                            <Select.Option key={index + 1} value={index + 1}>
                              {item}
                            </Select.Option>
                          );
                        })}
                    </Select>
                  )}
                </Form.Item>
              </Form.Item>

              <Form.Item {...formItemLayout} label="归属部门">
                {getFieldDecorator("ownerDept", {
                  rules: [
                    {
                      required: true,
                      message: "请选择归属部门"
                    }
                  ]
                })(
                  <TreeSelect
                    treeData={orgTree}
                    onChange={this.departGet}
                    style={{ width: 466 }}
                    dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                    showCheckedStrategy="SHOW_PARENT"
                    placeholder="请选择归属部门"
                  />
                )}
              </Form.Item>

              <Form.Item {...formItemLayout} label="管理员">
                {getFieldDecorator("owner", {
                  rules: [
                    {
                      required: true,
                      message: "请选择管理员"
                    }
                  ]
                })(
                  <div>
                    <Input
                      style={{ width: 466 }}
                      placeholder="请选择管理员"
                      onClick={() => {
                        this.setState({
                          selectVisible: true,
                          chooseOwner: true
                        });
                      }}
                      value={owner}
                    />
                  </div>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="告警渠道">
                {getFieldDecorator("reportChannel", {
                  rules: [
                    {
                      required: true,
                      message: "请选择告警渠道"
                    }
                  ]
                })(
                  <Select placeholder="请选择告警渠道" style={{ width: 466 }}>
                    {channelList.map(item => (
                      <Select.Option
                        value={item.pushChannelId * 1}
                        key={item.pushChannelId}
                      >
                        {item.description}
                      </Select.Option>
                    ))}
                  </Select>
                )}
              </Form.Item>

              <Form.Item {...formItemLayout} label="告警目标">
                {getFieldDecorator("alarmTargetTip", {
                  rules: [{ required: true, message: "请选择告警目标" }]
                })(
                  <div
                    className={
                      this.state.borderVisible
                        ? styles.address1
                        : styles.address
                    }
                    onClick={() => {
                      this.setState({
                        selectVisible: true,
                        chooseOwner: false
                      });
                    }}
                  >
                    {alarmTarget.length <= 0 ? (
                      <span
                        style={{
                          color: "rgba(0,0,0,0.25)",
                          height: 32,
                          marginTop: -5,
                          marginLeft: 12
                        }}
                      >
                        请选择告警目标
                      </span>
                    ) : (
                      alarmTarget.map((item, index) => (
                        <Tag
                          closable
                          onClose={e => this.onCloseTag(e, index)}
                          style={{
                            marginBottom: 5,
                            marginTop: 5,
                            marginLeft: 5,
                            zIndex: 500
                          }}
                          key={item}
                        >
                          {item}
                        </Tag>
                      ))
                    )}
                  </div>
                )}
              </Form.Item>

              <Form.Item {...formItemLayout} label="监控描述">
                {getFieldDecorator("monitorDescription", {
                  rules: [
                    {
                      max: 200,
                      message: "监控描述少于200个字"
                    }
                  ]
                })(
                  <TextArea
                    style={{ width: 466, height: 120 }}
                    placeholder="请输入监控描述"
                  />
                )}
              </Form.Item>
            </Form>
            <SelectModal
              select={chooseOwner ? manager : alarmTargetId}
              selectdesc={chooseOwner ? owner : alarmTarget}
              // select={manager}
              // selectdesc={owner}
              visible={selectVisible}
              closeModal={this.closeModal}
              confirm={this.confirm}
              // isMutiple={false}
              isMutiple={!chooseOwner} // 告警目标支持多选，管理员单选
              manager={true}
              reporter={!chooseOwner} // 告警目标
            />
          </div>
          <BottomInfo
            getLimitUnit={this.getLimitUnit}
            restrainUnit={restrainUnit}
            getRestrainUnit={this.getRestrainUnit}
            getLimitValue={this.getLimitValue}
            limitValue={limitValue}
            restrainValue={restrainValue}
            getRestrainValue={this.getRestrainValue}
            limitUnit={limitUnit}
          />
        </Spin>
      </FixedBottomWrapper>
    );
  }
}

export default SupervisoryAdd;
